package cn.xny.user.service.impl;

import cn.xny.basic.constant.WxConstants;
import cn.xny.basic.exception.BusinessException;
import cn.xny.basic.jwt.JwtUtils;
import cn.xny.basic.jwt.LoginData;
import cn.xny.basic.jwt.RsaUtils;
import cn.xny.basic.util.AjaxResult;
import cn.xny.basic.util.HttpUtil;
import cn.xny.basic.util.Md5Utils;
import cn.xny.basic.util.StrUtils;
import cn.xny.system.domain.Menu;
import cn.xny.user.domain.Logininfo;
import cn.xny.user.domain.User;
import cn.xny.user.domain.Wxuser;
import cn.xny.user.dto.LoginDto;
import cn.xny.user.mapper.LogininfoMapper;
import cn.xny.user.mapper.UserMapper;
import cn.xny.user.mapper.WxuserMapper;
import cn.xny.user.service.LogininfoService;
import cn.xny.basic.service.impl.BaseServiceImpl;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 业务实现类：
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements LogininfoService {

           @Autowired
          private LogininfoMapper logininfoMapper;


           @Autowired
           private RedisTemplate redisTemplate;

           @Autowired
           private WxuserMapper wxuserMapper;
           @Autowired
           private UserMapper userMapper;


    //账号登录
    @Override
    public Map<String, Object> accountLogin(LoginDto loginDto) {
        //判断不能为空值
        if (StringUtils.isEmpty(loginDto.getAccount()) || StringUtils.isEmpty(loginDto.getCheckPass())){
            throw new BusinessException("请填写账号和密码");
        }
        //判断账号
        Logininfo logininfo=logininfoMapper.loadByAccount(loginDto);
        if (logininfo==null){

            throw new BusinessException("账号错误");
        }
        //判断密码
        String inputMd5pwd = Md5Utils.encrypByMd5(loginDto.getCheckPass() + logininfo.getSalt());
        if (!inputMd5pwd.equals(logininfo.getPassword())){

            throw new BusinessException("密码错误");

        }
        //校验是否启用
        if (!logininfo.getDisable()){
            throw new BusinessException("该账号已被禁用，请联系管理员");

        }
//        //将登录信息保存到Redis当中
//        String token = UUID.randomUUID().toString();
//        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
//        //返回信息
//        Map<String,Object> map = new HashMap();
//            map.put("token",token);
//            logininfo.setPassword(null);
//            logininfo.setSalt(null);
//            map.put("logininfo",logininfo);

        Map<String, Object> map = loginSuccessJwtHandler(logininfo);

        return map;
    }
    //微信登录
    @Override
    public AjaxResult wechatLogin(Map<String, String> map) {
        //准备第二个的请求的地址
        String url = WxConstants.GET_ACK_URL.replace("APPID", WxConstants.APPID)
                .replace("SECRET", WxConstants.SECRET)
                .replace("CODE", map.get("code"));
        //使用httputil发送微信登录请求
        String jsonStr = HttpUtil.httpGet(url);
        //通过fastjson将json格式的字符串转成json的对象
        JSONObject jsonObj = JSONObject.parseObject(jsonStr);
        String access_token = jsonObj.getString("access_token");
        String openid = jsonObj.getString("openid");
        //通过openid查询t_wxuser表
        Wxuser wxuser = wxuserMapper.loadByOpenid(openid);
        if (wxuser != null) {
            User user = userMapper.loadByAll(wxuser.getUserId());
            if (user != null) {
                Logininfo logininfo = logininfoMapper.loadByAll(user.getLogininfoId());
//                //将登录信息保存到Redis当中
//                String token = UUID.randomUUID().toString();
//                redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
//                //返回信息
//                Map<String, Object> resultmap = new HashMap();
//                resultmap.put("token", token);
//                logininfo.setPassword(null);
//                logininfo.setSalt(null);
//                resultmap.put("logininfo", logininfo);
                Map<String, Object> resultmap = loginSuccessJwtHandler(logininfo);

                return AjaxResult.me().setObj(resultmap);
            }
        }
        //没有查到第一次扫码-到绑定页面
        return AjaxResult.me().setSuccess(false).setObj("?access_token="+access_token+"&openid="+openid);

    }

     //微信绑定
    @Override
    public AjaxResult wechatBinder(Map<String, String> map) {
        String phone = map.get("phone");
        String verifyCode = map.get("verifyCode");
        String accessToken = map.get("accessToken");
        String openId = map.get("openId");
        //1.校验-空值
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(verifyCode)){
            throw new BusinessException("信息不能为空!!!");
        }
        //2.校验-手机验证码：是否过期，是否正确:【业务键:电话号码 - 手机验证码:时间戳】
        Object obj = redisTemplate.opsForValue().get("binder:" + phone);
        if(obj==null){
            throw new BusinessException("手机验证码过期!!!");
        }
        if(!verifyCode.equals(obj.toString().split(":")[0])){
            throw new BusinessException("手机验证码错误!!!");
        }

        //3.准备第三个请求
        String url = WxConstants.GET_USER_URL.replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openId);
        //4.使用HttpUtil发送微信绑定请求 - 获取微信用户信息：返回jsonStr
        String jsonStr = HttpUtil.httpGet(url);
        //5.使用fastJson处理jsonStr - 将jsonObj中的数据转换Wxuser对象
        Wxuser wxuser = jsonStr2WxUser(jsonStr); //user_id=null
        //6.创建User对象和Logininfo对象【phone】 - 难度
        //因为：1.以前通过手机账号注册过，没有绑定微信
        User user = userMapper.loadByphone(phone);
        if(user==null){
            //手机号码没有绑定过
            user = phone2User(phone);
            Logininfo newLogininfo = user2Logininfo(user);

            logininfoMapper.save(newLogininfo);
            user.setLogininfoId(newLogininfo.getId());
            userMapper.save(user);
        }

        wxuser.setUserId(user.getId());//微信用户绑定User
        wxuserMapper.save(wxuser);
        //7.添加数据库：Logininfo对象 - User对象 - WxUser对象
        //8.做免密登录
        Logininfo logininfo = logininfoMapper.loadByAll(user.getLogininfoId());
//        String token = UUID.randomUUID().toString();
//        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
//        //6.返回信息：1.key - 后续每次发送请求都要携带这个可以，用于判断是否登录了2.登录信息 - 在前端页面显示账号
//        Map<String, Object> resultMap = new HashMap<>();
//        resultMap.put("token",token);
//        //响应给前端：将盐值和密码置空，提高安全性
//        logininfo.setSalt(null);logininfo.setPassword(null);
//        resultMap.put("logininfo",logininfo);
        Map<String, Object> resultMap = loginSuccessJwtHandler(logininfo);

        return AjaxResult.me().setObj(resultMap);
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        return logininfo;
    }

    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        String pwd = StrUtils.getComplexRandomString(12);
        String md5Pwd = Md5Utils.encrypByMd5(pwd + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        user.setState(1);
        return user;
    }

    private Wxuser jsonStr2WxUser(String jsonStr) {
        JSONObject obj = JSONObject.parseObject(jsonStr);
        Wxuser wxuser = new Wxuser();
        wxuser.setOpenid(obj.getString("openid"));
        wxuser.setNickname(obj.getString("nickname"));
        wxuser.setHeadimgurl(obj.getString("headimgurl"));
        wxuser.setUnionid(obj.getString("unionid"));
        return wxuser;
    }

    public Map<String,Object> loginSuccessJwtHandler(Logininfo logininfo){
        Map<String,Object> map = new HashMap<>();
        LoginData loginData = new LoginData();
        //设置logininfo值
        logininfo.setPassword(null);
        logininfo.setSalt(null);
        map.put("logininfo",logininfo);
        loginData.setLogininfo(logininfo);
        //设置permissions,menus值
         if (logininfo.getType()==0) {

             List<String> permissions = logininfoMapper.findPermissionsByLogininfoId(logininfo.getId());
             map.put("permissions", permissions);
             loginData.setPermissions(permissions);
             List<Menu> menus = logininfoMapper.findMenusByLogininfoId(logininfo.getId());
             map.put("menus", menus);
             loginData.setMenus(menus);
         }
           //设置加密token；

        try {
            PrivateKey  privateKey = RsaUtils.getPrivateKey(RsaUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());
            String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 30);
            map.put("token",jwtToken);

        } catch (Exception e) {
            e.printStackTrace();
        }


           return map;
    }


}
